package com.corn.turorial.spring.converter;

import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.stereotype.Component;
import org.springframework.util.ClassUtils;

import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author : Jim Wu
 * @version 1.0
 * @function :
 * @since : 2021/2/4 17:42
 */
public class MyMapHttpMessageConverter implements HttpMessageConverter<Map> {
    @Override
    public boolean canRead(Class<?> clazz, MediaType mediaType) {
        return false;
    }

    @Override
    public boolean canWrite(Class<?> clazz, MediaType mediaType) {
        // 根据媒体类型判断是不是我们自己的媒体类型
        if (mediaType != null && clazz.isAssignableFrom(Map.class)) {
            return mediaType.toString().equalsIgnoreCase("application/myContentType");
        }
        return ClassUtils.isAssignable(Map.class, clazz);
    }

    @Override
    public List<MediaType> getSupportedMediaTypes() {
        return Collections.singletonList(MediaType.parseMediaType("application/myContentType"));
    }

    @Override
    public Map read(Class<? extends Map> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        return null;
    }


    @Override
    public void write(Map map, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        // 写出
        Object result = map.keySet().stream().map(k -> k + "=" + map.get(k)).collect(Collectors.joining(",", "[", "]"));
        outputMessage.getBody().write(result.toString().getBytes());
    }
}
